package main

import (
	"fmt"
	"math"
	"sort"
)

/**
Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
*/

func threeSumClosest(num []int, target int) int {
	n, res, diff := len(num), 0, math.MaxInt32
	if n > 2 {
		//升序排列[-4,-1,1,2]
		sort.Ints(num)
		//预留剩余两个位置
		for i := 0; i < n-2; i++ {
			for j, k := i+1, n-1; j < k; {
				sum := num[i] + num[j] + num[k]
				if abs(sum-target) < diff {
					res, diff = sum, abs(sum-target)
				}
				if sum == target {
					//正好
					return res
				} else if sum > target {
					//结果大了，往小走
					k--
				} else {
					//结果小了，往大走
					j++
				}
			}
		}

	}
	return res
}

func abs(i int) int {
	if i > 0 {
		return i
	}
	return -i
}
func main() {
	num := []int{-1, 2, 1, -4}
	result := threeSumClosest(num, 1)
	fmt.Println(result)
}
